package jdbcRflect;

import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtils {
    @Test
    public static <T> List<T> list(String sql, Class<T> c) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {

        ArrayList<T> tlist = new ArrayList<>();
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shangluo?" +
                "useSSL=false&serverTimezone=UTC", "root", "123456");
        Statement statement = conn.createStatement();
        ResultSet rs = statement.executeQuery(sql);

        ResultSetMetaData md = rs.getMetaData();
//        System.out.println("根据结果获得了结果集中所以数据="+md);
        int count = md.getColumnCount();
        System.out.println("count="+count);

        while (rs.next()) {
            T t = c.newInstance();
            for (int i = 1; i < count + 1; i++) {
                Object value = rs.getObject(i);
                if (value != null) {
                    String columnName = md.getColumnName(i);
//                    System.out.println("columnName = " + columnName);
                    Field f = c.getDeclaredField(columnName);
                    f.setAccessible(true);
                    f.set(t, value);
                }
                tlist.add(t);
            }
        }

        return tlist;
    }
}
